package cn.wrl.auth.service.impl;


import cn.wrl.auth.service.AuthService;
import cn.wrl.auth.service.pojo.Account;
import cn.wrl.auth.service.pojo.AuthCode;
import cn.wrl.auth.service.pojo.AuthResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class AuthServiceImpl implements AuthService {

    public static final String REDIS_USER_TOKEN = "REDIS_USER_TOKEN:";
    public static final String REDIS_USER_REFRESH_TOKEN = "REDIS_USER_REFRESH_TOKEN:";


    @Autowired
    private JwtService jwtService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public AuthResponse tokenize(String userId) {
        Account account = Account.builder()
                .userId(userId)
                .token(jwtService.token(userId))
                .refreshToken(UUID.randomUUID().toString())
                .build();

        redisTemplate.opsForValue().set(REDIS_USER_TOKEN + userId, account);
        redisTemplate.opsForValue().set(REDIS_USER_REFRESH_TOKEN + account.getRefreshToken(), userId);

        return AuthResponse.builder()
                .account(account)
                .code(AuthCode.SUCCESS.getCode())
                .build();

    }

    @Override
    public AuthResponse verify(Account account) {
        boolean verify = jwtService.verify(account.getToken(), account.getUserId());

        return AuthResponse.builder()
                .code(verify ? AuthCode.SUCCESS.getCode() : AuthCode.USER_NOT_FOUND.getCode())
                .build();
    }

    @Override
    public AuthResponse refresh(String refresh) {
        String userId = (String) redisTemplate.opsForValue().get(refresh);
        if (StringUtils.isBlank(userId)) {
            return AuthResponse.builder()
                    .code(AuthCode.USER_NOT_FOUND.getCode())
                    .build();
        }

        return tokenize(userId);
    }

    @Override
    public AuthResponse delete(Account account) {
        AuthResponse verify = verify(account);
        if (verify.isOk()) {
            redisTemplate.delete(REDIS_USER_TOKEN + account.getUserId());
            redisTemplate.delete(REDIS_USER_REFRESH_TOKEN + account.getRefreshToken());
            return AuthResponse.builder()
                    .account(account)
                    .code(AuthCode.SUCCESS.getCode())
                    .build();
        }
        return AuthResponse.builder()
                .code(AuthCode.USER_NOT_FOUND.getCode())
                .build();
    }
}
